package com.example.fashionshoes.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fashionshoes.constant.JwtConst;
import com.example.fashionshoes.exception.BusinessException;
import com.example.fashionshoes.mapper.CollectionMapper;
import com.example.fashionshoes.pojo.dto.CollectionPageDTO;
import com.example.fashionshoes.pojo.po.Collections;
import com.example.fashionshoes.pojo.po.Goods;
import com.example.fashionshoes.pojo.vo.CollectionVo;
import com.example.fashionshoes.service.CollectionService;
import com.example.fashionshoes.service.GoodsService;
import com.example.fashionshoes.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collections> implements CollectionService {

    @Resource
    private CollectionMapper collectionMapper;
    @Resource
    private GoodsService goodsService;

    /**
     * 收藏商品
     *
     * @param goodsId 商品id
     */
    @Override
    public void saveCollection(Integer goodsId) throws BusinessException {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        //如果以及收藏
        Collections collections = lambdaQuery().eq(Collections::getGoodsId, goodsId).eq(Collections::getUserId,userId).one();
        if (collections != null) {
            throw new BusinessException("该商品你已收藏");
        }
        Goods goods = goodsService.lambdaQuery().eq(Goods::getId, goodsId).one();
        Collections collection = BeanUtil.copyProperties(goods, Collections.class);
        collection.setId(null);
        collection.setGoodsId(goodsId);
        collection.setUserId(userId);
        save(collection);
    }

    /**
     * 获取收藏商品列表
     * @param collectionPageDTO 分页数据
     * @return 收藏商品列表
     */
    @Override
    public CollectionVo getPageCollectionList(CollectionPageDTO collectionPageDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(JwtConst.USER_ID);
        collectionPageDTO.setUserId(userId);
        Page<Object> objects = PageHelper.startPage(collectionPageDTO.getPage(), collectionPageDTO.getPageSize());
        Page<Collections> page = collectionMapper.getPageCollectionList(collectionPageDTO);
        objects.close();
        return CollectionVo.builder()
                .pages(page.getPages())
                .pageSize(page.getPageSize())
                .collectionsList(page.getResult())
                .build();
    }
}
